import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import {
  ClearHistoriesAction,
  ClearsuggestAction,
  GetKeywordBysuggestAction,
  SaveKeyWordHistoryAction,
} from '@/store/action/search';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';
import DOMPurify from 'dompurify';
import { SetKeyWordHistory } from '@/utils/storage';
import { Toast } from 'antd-mobile';
import { useHistory } from 'react-router-dom';
export default function Search() {
  const [keyWord, setKeyWord] = useState('');
  const { suggestion, Histories } = useAppSelector((state) => state.search);
  const dispatch = useDispatch();
  const history = useHistory();
  /** 搜索事件 */
  const handleSubmit = async (key: string) => {
    if (key.trim()) {
      setKeyWord(key.trim());
      await dispatch(SaveKeyWordHistoryAction(key.trim()));
      history.push(`/search/result/${key}`);
    } else {
      Toast.show('搜索内容不能为空');
    }
  };

  /** 监听Histories变化实现本地储存 */
  useEffect(() => {
    SetKeyWordHistory(Histories);
  }, [Histories]);

  /** 输入框回车事件 */
  const handleEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') handleSubmit(keyWord);
  };

  /** 搜索防抖事件处理 */
  const TimeIdRef = useRef(-1);
  const handleChangeKeyWord = (e: React.ChangeEvent<HTMLInputElement>) => {
    setKeyWord(e.target.value);
    clearTimeout(TimeIdRef.current);
    if (e.target.value.trim()) {
      TimeIdRef.current = window.setTimeout(() => {
        dispatch(GetKeywordBysuggestAction(e.target.value.trim()));
      }, 500);
    }
  };

  /** 卸载时清除定时器 */
  useEffect(() => {
    return () => {
      clearTimeout(TimeIdRef.current);
      dispatch(ClearsuggestAction());
    };
  }, [dispatch]);

  /** 使用正则处理搜索高亮 */
  const highquantity = (keyWord: string, item: string) => {
    /** 细节优化:正则替换高量时,不能改变大小写 */
    /** 使用$1表示第一个小括号中匹配到的内容 */
    return item.replace(
      new RegExp(`(${keyWord.trim()})`, 'ig'),
      `<span>$1</span>`
    );
  };

  /** 清空按钮事件 */
  const handleclear = () => {
    dispatch(ClearsuggestAction());
    setKeyWord('');
  };

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        right={
          <span className="search-text" onClick={() => handleSubmit(keyWord)}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              type="text"
              placeholder="请输入关键字搜索"
              value={keyWord}
              onKeyDown={(e) => handleEnter(e)}
              onChange={(e) => handleChangeKeyWord(e)}
            />

            {/* 清空输入框按钮 */}
            {!!keyWord.trim() && (
              <Icon
                type="iconbtn_tag_close"
                className="icon-close"
                onClick={() => handleclear()}
              />
            )}
          </div>
        </div>
      </NavBar>

      {!!!keyWord.trim() ? (
        /* 搜索历史 */
        <div className="history" style={{ display: 'block' }}>
          <div className="history-header">
            {Histories.length > 0 && (
              <>
                <span>搜索历史</span>
                <span onClick={() => dispatch(ClearHistoriesAction())}>
                  <Icon type="iconbtn_del" />
                  清除全部
                </span>
              </>
            )}
          </div>

          <div className="history-list">
            {Histories.slice(0, 10).map((item, index) => {
              return (
                <span
                  className="history-item"
                  key={index}
                  onClick={() => handleSubmit(item)}
                >
                  {item}
                  <span className="divider"></span>
                </span>
              );
            })}
          </div>
        </div>
      ) : (
        /* 搜素建议结果列表 */
        <div className="search-result">
          {suggestion.map((item, index) => {
            return (
              <div
                className="result-item"
                key={index}
                onClick={() => handleSubmit(item)}
              >
                <Icon className="icon-search" type="iconbtn_search" />
                <div className="result-value">
                  <div
                    dangerouslySetInnerHTML={{
                      __html: DOMPurify.sanitize(highquantity(keyWord, item)),
                    }}
                  ></div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
